package com.atqar.safe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class Nosafe {
    public static void main(String[] args) {
        //listnosafe();

        //setnosafe();
        mapnosafe();

    }

    public static void mapnosafe(){
        //concurrenthashmap 分段锁并发安全的HashMap，底层采用数组、链表、红黑树内部大量采用CAS操作。并发控制使⽤synchronized和CAS来操作来实现的
        Map<String, String> map = new ConcurrentHashMap<>(); //Collections.synchronizedMap(new HashMap<>());//new HashMap<>();
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,6));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }

    public static void setnosafe(){
        //copyonwriter
        Set<Object> set = new CopyOnWriteArraySet<>();Collections.synchronizedSet(new HashSet<>());//new HashSet<>();阈值12时候会自动扩容扩容一倍底层是hashmap
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(set);
            }).start();
        }
    }


    public static void listnosafe(){
        //copyonwriter 读写分离,写时复制,用于读多写少时
        List<Object> list = new CopyOnWriteArrayList<>();//Collections.synchronizedList(new ArrayList<>());//new Vector<>(); //new ArrayList<>();//object[10]  ,是线程不安全的会报java.util.ConcurrentModificationException,线程并发修改异常
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(list);
            }).start();
        }
    }
}
